//
//  WebConnection.m
//  Growth
//
//  Created by Hobo.Chen on 1/5/12.
//  Copyright 2012 MEETStudio. All rights reserved.
//

#import "WebConnection.h"
#import "CJSONDeserializer.h"

@interface WebConnection (Private)

- (void)connectionFinished:(NSDictionary *)feedDictionary;

- (void)connectionError:(NSError *)error;

//post success
- (void)postFinished:(NSString *)recieveInfo;

@end


@implementation WebConnection

@synthesize connectionDelegate;
@synthesize jsonData;
@synthesize dataBaseListName;

- (id)initWith:(NSMutableURLRequest *)request delegate:(id)delegate dataBaseListName:(NSString *)listName{
	self.connectionDelegate = delegate;
	
    self.dataBaseListName=listName;
    
	[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
	
	
	jsonData = [[NSMutableData data] retain];
    
    return self;

    
}


- (NSDictionary *)parseJSON:(NSMutableData *)data {
	CLog(@"Parsing JSON");
	NSError *error = nil;
    
        
	NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&error];
	CLog(@"connection data dict %@",dictionary);
    
    //数据缓存
    NSString *string=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

     diaryId=[[dictionary objectForKey:@"id"] intValue];
     
	[self saveDataToDatabaseWithType:self.dataBaseListName stringData:string];
    
	return dictionary;
}

// NSURLConnection Delegate Methods. You would want to include more for error handling //
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
//    NSDictionary *headerFields = [response allHeaderFields]; 
// 
//    NSURL *url = connection.originalRequest.URL;  
//    
//    CLog(@"login  URL %@", url);
//   
//    CLog(@"login  headerField %@",headerFields);
//  
//    CLog(@"login  cookie %@", [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url]);
//
//    NSHTTPCookie *cookie = [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url] objectAtIndex:0] ;
//     NSString *session = [NSString stringWithFormat:@"%@=%@",[cookie name],[cookie value]];
//    CLog(@"seesion %@", session);

    
    //[[NSUserDefaults standardUserDefaults] setValue:session forKey:@"cookie"];
    
    
    NSHTTPURLResponse  *httpResponse = ( NSHTTPURLResponse  *)response;
    
    
    statusCode = [httpResponse  statusCode ];
    
    
    NSLog ( @"status code = %d" ,statusCode);
    
    
    if  (statusCode !=  200 ){//网络错误
        
        CLog(@"网络%d错误",statusCode);
         NSError *error=nil;
        
        [self connectionFaild:error];

        
    }

        
	
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSMutableData *)data {
	CLog(@"Recieving Data...");
	// Append the incomming data as it is received
	[jsonData appendData:data];
	NSString *stringData = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
	//CLog(@"connection data %@",jsonData);
	CLog(@"connection data encode %@",stringData);
    
    
    if ([stringData isKindOfClass:[NSNull class]]) {
         stringData=@"false";
    }
   // [self postFinished:stringData];
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	
	CLog(@"connection error: %@", error);
	[self connectionFaild:error];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	CLog(@"Fininshed Loading...");

    if (statusCode == 200) {
        
        NSDictionary * feedDictionary = [self parseJSON:jsonData];
	
	    [self connectionFinished:feedDictionary];

    }
    
		
	//CLog(@"JSON as NSDictionary:: %@", feedDictionary);
}


#pragma mark -Delegate
- (void)connectionFinished:(NSDictionary *)feedDictionary{
    
     
	if (connectionDelegate != nil) {
        if ([connectionDelegate respondsToSelector:@selector(connectionSuccess:)]) {
            [connectionDelegate connectionSuccess:feedDictionary];
        }
		
	}
     
    
}

- (void)connectionFaild:(NSError *)error{
	
    CLog(@"connectionFaild Error %@", error);
    
	if (connectionDelegate != nil) {
        
//        //NSString *domain = [error domain];
//        NSInteger errorCode = [error code];
//        //NSString *localizedDescription = [error localizedDescription];
//        
//        CLog(@"Error code %d", errorCode);
//        
//        if (errorCode == -1001) {
//            [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求超时，请检查网络状态！" duration:DEFAULT_LOADING_TIME /2];
//        }
//        else {
//            [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误，请检查网络状态！" duration:DEFAULT_LOADING_TIME /2];
//        }
        
        if ([connectionDelegate respondsToSelector:@selector(connectionError:)]) {
            [connectionDelegate connectionError:error];
        }
		
	}
    
}

- (void)postFinished:(NSString *)recieveInfo{
    if (connectionDelegate != nil) {
        if ([connectionDelegate respondsToSelector:@selector(postSuccess:)]) {
            [connectionDelegate postSuccess:recieveInfo];
        }
		
	}
    
}





#pragma mark -save data to dataBase

#pragma mark -save data to database
-(void)saveDataToDatabaseWithType:(NSString *)listType stringData:(NSString *)stringData{
    
    if (listType==nil) {
        return;
    }
    
      PublicDatabaseEngine *databaseEngine = [PublicDatabaseEngine sharedDatabaseEngine];
    
    int timelineId = [[[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] intValue];   

    //时间轴宝宝信息
    if ([listType isEqualToString:@"TimelineInfo"]) {
        
        NSString *sql = [NSString stringWithFormat:@"insert or replace into TimelineInfo (tid,json) values (%d, '%@')", timelineId,stringData];
        
        [databaseEngine executeSQL:sql];
        
        
    }
    
   
    
}



@end
